// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;

//1. Point out the bugs in these functions
//a. The following function should return 0-terminated string containing hexadecimal
//representation of integer number as 0x00FFFFFF:
//0x00FFFFFF
//0x00000000
char* hex_str( int i )
{
    //char res[]="0x00000000";
    //int len =sizeof(res)/sizeof(char);
    int len = 11;
    char *res = new char[len];
    char digits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    int mask=15;
    
    res[0]='0';
    res[1]='x';

    for ( int j=len-2; j >= 2 ; j-- )
    {
        res[j]= digits[i & mask];
        i >>=4;
    }
    res[10] = '\0';
    return res;
}

// get bit at pos
bool getBit(int num, int pos )
{
    int mask = 1 << pos;
    return ( mask & num != 0 );

}

// set bit at pos
int setBit(int num, int pos)
{
    int mask = 1 << pos;
    return ( num | mask );
}

// clean bit at pos
int cleanBit(int num, int pos)
{
    int mask = ~( 1<<pos );
    return num & mask;
}

// clean bits from most significant bit through pos
int cleanBitsLeft2i(int num, int pos)
{
    int mask = (1 << pos) - 1;
    return num & mask;
}

// clean bits from pos through 0
int cleanBitsRight2i(int num, int pos)
{
    int mask = ~(1 << (pos+1) - 1);
    return num & mask;
}


int main () {
    char * test = hex_str( 16777215 );
    cout << test << endl;
    printf("hex: %s \n", test );
    exit(0);

    char abc[] = "abc";
    char abd[] = "abc\0";
    cout << sizeof(abc)/sizeof(char) << " , " << sizeof(abd)/sizeof(char) << endl;

    exit(0);
    // bitwise
    // change positive integer to neative integer
    int a = 10;
    int b = ~a;  // flip the bits
    int c = b + 1; // add 1
    cout << a << " change to negative by bitwise: " << c << endl;
   
    // int >> 1 = int / 2
    int d = 4;
    int e = d >> 1;
    cout << d << " shift right by 1 bit: " << e << endl;

    // int << 1 = int * 2
    int f = 4;
    int g = f << 1;
    cout << f << " shift right by 1 bit: " << g << endl;
  return 0;
}
